# -*- coding: utf-8 -*-
import requests,time,pymysql,random
import urllib.request,urllib.error
import os,re,IPy
from multiprocessing import Pool

def use17CE(host):
    URL = "https://www.17ce.com/site/dns"
    HEAD = {
        "Host": "www.17ce.com",
        "Connection": "keep-alive",
        "Content-Length": "250",
        "Origin": "https://www.17ce.com",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
        "Content-type": "application/x-www-form-urlencoded",
        "Accept": "*/*",
        "Referer": "https://www.17ce.com/",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.8"
    }

    DATA = {
        "url":host,
        "curl": "",
        "rt": "1",
        "nocache": "0",
        "host": "",
        "referer": "",
        "cookie": "",
        "agent": "",
        "speed": "",
        "postfield": "",
        "verify": "6193947fd0f85f5c1c30e0b5a0eae99f07dd7206",
        "pingcount": "",
        "pingsize": "",
        "area[]": ["1"],
        "isp[]": ["0", "1", "2", "6", "7", "8", "4"]
    }

    r = requests.post(url=URL, data=DATA, headers=HEAD)
    r.encoding = "utf8"
    aa = r.json()
    print(aa)
    retry=0
    while(True):
        try:
            tid = aa["tid"]
            print(tid)
            break

        except:
            if retry==3:
                print("重试3次失败，跳过")
                break
            retry=retry+1
            print("17ce请求失败，进行第%d次尝试，" % retry)
            pass
    ipList = []
    num = "0"
    while (True):
        rr = requests.post(url="https://www.17ce.com/site/ajaxfresh", data={"tid": tid, "num": num, "ajax_over": "0"}, headers=HEAD)
        rr.encoding = "utf8"
        RES = rr.text
        print(RES)
        ip = re.findall("\d+\.\d+\.\d+\.\d+", str(RES))
        ipList.extend(ip)
        print(ip)
        try:
            num = re.findall('"num2"\:"\d+"', str(RES))
            num = num[0].split(":")[1].replace('"', "")
            print("num2", num)
        except:
            break
        if re.match("\d+", num):
            pass
        else:
            break
    return ipList


def CDN(ip):
    try:
        for x in DDIP:
            if ip in IPy.IP(x[0]):
                print(ip, "已存在：", x[1])
                return "已存在：" + x[1]
        print(ip, "不存在")
        return "不存在"
    except:
        print(ip, "不存在")
        return "不存在"


def read_excel(file):#读取调度IP，生成列表
    DDIP=xlrd.open_workbook(file)
    #print(DDIP.sheet_names())
    DDIP_sh= DDIP.sheet_by_index(0)
    row_num=DDIP_sh.nrows
    #print(row_num)
    DDIP_list=[]
    for x in range(row_num):
        #print(DDIP_sh.row_values(x))
        DDIP_list.append(DDIP_sh.row_values(x))
    #print(DDIP_list)
    #DDIP_list.pop(0)
    return  DDIP_list

def updateDB(IP,exist="不存在"):#[ip,cp,domain]
    db=pymysql.connect("113.215.1.161","root","root","mydb",charset="utf8" )# 打开数据库连接
    cursor = db.cursor()# 使用cursor()方法获取操作游标
    #查询
    sqlFind='SELECT * FROM IPcheckTab WHERE IP="%s"' % IP[0]
    #更新
    sqlupdate='UPDATE IPcheckTab SET CP="%s",domain="%s",exist="%s" WHERE IP="%s" ' % (IP[1],IP[2],exist,IP[0])
    #插入
    sqlInsert='INSERT INTO IPcheckTab(IP,CP,domain,exist) VALUES ("%s","%s","%s","%s")' % (IP[0],IP[1],IP[2],exist)
    print(sqlFind)
    Find=cursor.execute(sqlFind)
    print("找到%s条记录" % Find)
    if Find==0:#如果库中无次记录
        try:
            cursor.execute(sqlInsert)  # 插入记录
            print(sqlInsert,"插入成功")
        except:
            print(sqlInsert,"插入失败")
            db.close()
            return 0
    else:
        try:
            cursor.execute(sqlupdate)#更新记录
            print(sqlupdate,"更新成功")
        except:
            print(sqlupdate, "更新失败")
            db.close()
            return 0
    db.close()

def readDB(DBname):
    db = pymysql.connect("113.215.1.161", "root", "root", "mydb", charset="utf8")  # 打开数据库连接
    cursor = db.cursor()  # 使用cursor()方法获取操作游标
    sql = "SELECT * FROM %s" % DBname
    cursor.execute(sql)
    results = cursor.fetchall()
    db.close()
    return results



def main(hostANDcp):
    host=hostANDcp[1]
    CP=hostANDcp[0]

    AnserList = []

    print("正在域名解析",host,CP)

    anwser1=use17CE(host)
    print(host, "17ce", anwser1)

    for i in list(set(anwser1)):
            AnserList.append([i,CP,host])
    for x in AnserList:
        exist = CDN(x[0])
        print(x,exist)
        #updateDB(x, exist)







if __name__ == '__main__':
    #download_xls("http://113.215.1.161/DD_Domain/DDIP_Domain.xlsx")
    DDIP=readDB("DDIPtab")
    print("调度表加载完毕")
    #hostlist=read_excel("DDIP_Domain.xlsx")
    hostlist = [("爱奇艺","cache.m.ptqy.gitv.tv")]
    print("加载调度控制域名")

    #print(hostlist)
    DD_Dict={}
    res=[]
    for host in hostlist:
        main(host)

    '''
    for i in res:
        for j in i:
            print(j)
            DD_Dict[j[0]]=j,
    for IP in DD_Dict:
        updateDB(DD_Dict[IP])
    IPcheckTab=readDB("IPcheckTab")
    for x in IPcheckTab:
        x=list(x)
        exist=CDN(x[0])
        x.pop()
        updateDB(x,exist)

'''







